// static/js/script.js
let balanceChart = null; // Global chart instance for updating

// Function to load accounts and populate lists/modals
function loadAccounts() {
    axios.get('/api/accounts')
        .then(response => {
            const accounts = response.data;
            const accountList = document.getElementById('account-list');
            accountList.innerHTML = '';
            accounts.forEach(acc => {
                const card = document.createElement('div');
                card.className = 'col-md-4 mb-3';
                card.innerHTML = `
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Account ID: ${acc.id}</h5>
                            <p class="card-text">Name: ${acc.name}<br>Balance: $${acc.balance.toFixed(2)}</p>
                            <a href="/history/${acc.id}" class="btn btn-primary">View History</a>
                        </div>
                    </div>
                `;
                accountList.appendChild(card);
            });

            // Populate select options for modals and chart selector
            const selects = [
                document.getElementById('deposit-account'),
                document.getElementById('withdraw-account'),
                document.getElementById('from-account'),
                document.getElementById('to-account'),
                document.getElementById('chart-account-selector')
            ];
            selects.forEach(select => {
                if (select) {
                    select.innerHTML = '<option value="">Select an account</option>';
                    accounts.forEach(acc => {
                        const option = document.createElement('option');
                        option.value = acc.id;
                        option.textContent = `${acc.id} - ${acc.name} (Balance: $${acc.balance.toFixed(2)})`;
                        select.appendChild(option);
                    });
                }
            });

            // Load chart for the first account if available
            if (accounts.length > 0) {
                loadChart(accounts[0].id);
            } else {
                document.getElementById('no-data-message').classList.remove('d-none');
            }
        })
        .catch(error => {
            console.error('Error loading accounts:', error);
            const alertContainer = document.getElementById('alert-container');
            alertContainer.innerHTML = `
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    Error loading accounts: ${error.message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>`;
        });
}

// Function to load and render balance history chart
function loadChart(accountId) {
    const ctx = document.getElementById('balanceChart').getContext('2d');
    const noDataMessage = document.getElementById('no-data-message');

    if (!accountId) {
        noDataMessage.classList.remove('d-none');
        if (balanceChart) balanceChart.destroy();
        return;
    }

    axios.get(`/api/balance_history/${accountId}`)
        .then(response => {
            const history = response.data;
            if (history.length === 0) {
                noDataMessage.classList.remove('d-none');
                if (balanceChart) balanceChart.destroy();
                return;
            }

            noDataMessage.classList.add('d-none');
            const labels = history.map(item => item.date);
            const data = history.map(item => item.balance);

            // Destroy previous chart if exists
            if (balanceChart) balanceChart.destroy();

            balanceChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: `Balance History for Account ${accountId}`,
                        data: data,
                        borderColor: '#007BFF',
                        backgroundColor: 'rgba(0, 123, 255, 0.1)',
                        fill: true,
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: 'Date'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: 'Balance ($)'
                            },
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        legend: {
                            display: true
                        }
                    }
                }
            });
        })
        .catch(error => {
            console.error('Error loading balance history:', error);
            noDataMessage.classList.remove('d-none');
            if (balanceChart) balanceChart.destroy();
            const alertContainer = document.getElementById('alert-container');
            alertContainer.innerHTML = `
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    Error loading balance history: ${error.message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>`;
        });
}

// Simulate button
document.getElementById('simulate-btn').addEventListener('click', () => {
    const progress = document.getElementById('simulate-progress');
    progress.classList.remove('d-none');
    let width = 0;
    const interval = setInterval(() => {
        width += 20;
        progress.querySelector('.progress-bar').style.width = `${width}%`;
        if (width >= 100) clearInterval(interval);
    }, 500);

    axios.post('/simulate')
        .then(response => {
            const log = document.getElementById('simulation-log');
            log.innerHTML = response.data.log.map(entry => `<li class="list-group-item">${entry}</li>`).join('');
            new bootstrap.Modal(document.getElementById('simulationModal')).show();
            progress.classList.add('d-none');
            loadAccounts(); // Refresh accounts and chart
        })
        .catch(error => {
            console.error('Simulation error:', error);
            progress.classList.add('d-none');
            const alertContainer = document.getElementById('alert-container');
            alertContainer.innerHTML = `
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    Simulation error: ${error.message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>`;
        });
});

// Form submissions
const forms = [
    { id: 'create-form', url: '/create_account' },
    { id: 'deposit-form', url: '/deposit' },
    { id: 'withdraw-form', url: '/withdraw' },
    { id: 'transfer-form', url: '/transfer' }
];

forms.forEach(formInfo => {
    const form = document.getElementById(formInfo.id);
    if (form) {
        form.addEventListener('submit', e => {
            e.preventDefault();
            const formData = new FormData(form);
            const loadingModal = new bootstrap.Modal(document.getElementById('loadingModal'));
            loadingModal.show();

            axios.post(formInfo.url, formData)
                .then(response => {
                    loadingModal.hide();
                    const alertContainer = document.getElementById('alert-container');
                    const alert = document.createElement('div');
                    alert.className = 'alert alert-success alert-dismissible fade show';
                    alert.innerHTML = `${response.data.message} <button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
                    alertContainer.appendChild(alert);
                    loadAccounts(); // Refresh accounts and chart
                    bootstrap.Modal.getInstance(form.closest('.modal')).hide();
                })
                .catch(error => {
                    loadingModal.hide();
                    const alertContainer = document.getElementById('alert-container');
                    const alert = document.createElement('div');
                    alert.className = 'alert alert-danger alert-dismissible fade show';
                    alert.innerHTML = `Error: ${error.response ? error.response.data.error : error.message} <button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
                    alertContainer.appendChild(alert);
                });
        });
    }
});

// Chart account selector
document.getElementById('chart-account-selector').addEventListener('change', (e) => {
    const accountId = e.target.value;
    loadChart(accountId);
});

// Init
document.addEventListener('DOMContentLoaded', () => {
    loadAccounts();
    console.log('Page loaded, initializing accounts and chart');
});